import { ref, onMounted } from 'vue'

/**
 * 描述
 * @date 2023-01-27
 * @param {any} fn:(...args:any[]
 * @returns {any} debounced
 */
export function useDebounce(fn: (...args: any[]) => any, delay = 200) {
  const timeout = ref<NodeJS.Timeout | null>(null)
  function debounced(...args: any[]) {
    if (timeout.value) clearTimeout(timeout.value)
    timeout.value = setTimeout(() => {
      fn(...args)
      timeout.value = null
    }, delay)
  }
  onMounted(() => {
    return () => {
      if (timeout.value) clearTimeout(timeout.value)
    }
  })
  return debounced
}
